package com.lanhai.longheng;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector; 
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
 

/**
 * TCP,消息协议
 * @author zhengwei
 *
 */
public class MsgCore { 
	 boolean 	running=true; 
	static  Map<Integer,String> sendMap=Collections.synchronizedMap(new HashMap<Integer,String>());
	Thread th;
	String ip;
	 IoConnector connector ;
	 static  IoSession session ;
	 
	 
	public MsgCore(String ip) { 
		 this.ip=ip;
		 connector = new NioSocketConnector(); 
         connector.setConnectTimeoutMillis(30000);
         connector.getFilterChain().addLast("codec",
                 new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"),
                         LineDelimiter.NUL.getValue(), 
                         LineDelimiter.NUL.getValue())));
         connector.setHandler(new MsgHandler());
	}
	 
	void connect() {
		try {
			ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", 8012));
			future.awaitUninterruptibly();

			// 连接成功后获取会话对象。如果没有上面的等待，由于connect()方法是异步的，session可能会无法获取。
			session = future.getSession();
		} catch (Exception e) {
			session = null;
		}

	}
	
	
	public void Start() {
		running=true;
		th=new Thread() { 
			@Override
			public void run() {
				 while(running) {
					if(connector.isActive()==false) {
						System.out.println("开始重连接"); 
						connect();
			         } else {
			        	 try {
								Thread.sleep(100);
							} catch (InterruptedException e) {
								 
							}
			         }
					
				 }
			}
			
		};
		connect();
		th.start();
	}
	
	public void Stop() {
		running=false;
		try {
			if(session!=null) {

		         session.close(true);
		         session=null;
			} 
			if(th!=null) {
				th.interrupt();
				th=null;
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		 
	} 
	
	
	public static void sendMsg(int agvid,String msg) {
		if (session == null) {
			//logger.error(String.format( "没有websocket连接，无法向AGV【%d】发送消息：【%s】",agvid,msg));
		} else {

			String tp = sendMap.get(agvid);
			if (tp != null && tp.equals(msg)) {
				return;
			}

			sendMap.put(agvid, msg);
			String msgp = "{receiver:'no" + agvid + "_agv',data:'" + msg + "'}";
			try {
				session.write(msgp);
			} catch (Exception ex) {
			}
		}
	}
}
